package cn.com.egova.permission.dispatcher;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import cn.com.egova.permission.R;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 1.注解作用的方法不可以是private, 官方是直接不要修饰符, 不过public也可以;
 * 2.操作流程:a)添加注释; b)编译,自动生成1个类.
 * 只有@RuntimePermissions和@NeedsPermission是必须的,其余注解均为可选.当使用了@RuntimePermissions和
 * @NeedsPermission之后,需要点击菜单栏中Build菜单下的Make Project,或者按快捷键Ctrl + F9编译整个项目,
 * 编译器会在app\build\intermediates\classes\debug目录下与被注解的Activity同一个包下生成一个辅助类,
 * 名称为被注解的Activity名称+PermissionsDispatcher.class
 * 3.参考资料:
 * http://www.jianshu.com/p/d6110f586d68
 * https://github.com/hotchemi/PermissionsDispatcher
 */

@RuntimePermissions
public class DispatcherActivity extends AppCompatActivity {
    private static final String TAG = "DispatcherActivity";
    private Button btn_call;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispatcher);

        initData();

        initActionBar();

        initView();
    }

    private void initData() {
        title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = "Permission";
        }
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(title);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(false);
        }
    }

    private void initView() {
        btn_call = (Button) findViewById(R.id.btn_call);
        btn_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){  //23,Android 6.0
                    DispatcherActivityPermissionsDispatcher.callWithCheck(DispatcherActivity.this);
                }else{
                    call();
                }
            }
        });
    }

    @NeedsPermission({Manifest.permission.CALL_PHONE,Manifest.permission.CAMERA})
    void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri uri = Uri.parse("tel:" + "10086");
            intent.setData(uri);
            startActivity(intent);
            Toast.makeText(this, "打电话啦", Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    @OnShowRationale({Manifest.permission.CALL_PHONE,Manifest.permission.CAMERA})
    void showRationale(final PermissionRequest request) {
//        request.proceed(); // 提示用户权限使用的对话框
        new AlertDialog.Builder(this)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("本应用需要电话和相机的权限,应用将要申请电话和相机权限")
                .show();
    }

    @OnNeverAskAgain({Manifest.permission.CALL_PHONE,Manifest.permission.CAMERA})
    void onNeverAskAgain() {
        new AlertDialog.Builder(this)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO: 2017/05/04 打开系统设置权限
                        Intent intent = new Intent();
                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("您已经禁止了电话和相机权限,是否现在去开启")
                .show();
    }


    /**
     * 如果用户拒绝该权限执行的方法
     */
    @OnPermissionDenied({Manifest.permission.CALL_PHONE,Manifest.permission.CAMERA})
    void onPermissionDenied() {
        Toast.makeText(this, "禁止电话和相机权限将无法使用本应用", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        DispatcherActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }else{
            return super.onOptionsItemSelected(item);
        }
    }
}
